package com.doit.day01;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class ZKClientDemo {
    public static void main(String[] args) throws Exception {
        String zkConnect = "linux01:2181,linux02:2181,linux03:2181";
        int timeOut = 1000;
        //获取zk对象
        ZooKeeper zk = new ZooKeeper(zkConnect, timeOut, null);

        //调用api进行操作
//        getAllChildren("/",zk);
//        zk.delete("/aaa",-1);

        //没有递归删除的方法，要写一个递归删除的方法
//        rmr("/ccc",zk);
//        getAllChildren("/",zk);


        //create
        /*
        ZooDefs.Ids.OPEN_ACL_UNSAFE  所有的权限
        ZooDefs.Ids.CREATOR_ALL_ACL  创建者所有的权限
        ZooDefs.Ids.READ_ACL_UNSAFE  只读权限


        PERSISTENT  持久的
        EPHEMERAL  临时的   -e
        EPHEMERAL_SEQUENTIAL  临时有序  -e -s
        PERSISTENT_SEQUENTIAL  持久有序  -s
         */

//        for (int i = 0; i < 3; i++) {
//            zk.create("/teachers/abc","teachers".getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
//        }

        //set
        zk.setData("/teachers","aaa".getBytes(StandardCharsets.UTF_8),-1);

        //get
        byte[] data = zk.getData("/teachers", null, null);
        System.out.println(new String(data));

        //关闭资源
        zk.close();
    }

    //没有递归删除的方法，要写一个递归删除的方法
    private static void rmr(String path, ZooKeeper zk) throws Exception {
        List<String> children = zk.getChildren(path, null);
        if (children.size() > 0){
            for (String child : children) {
                rmr(path+"/"+child,zk);
            }
        }
        zk.delete(path,-1);
    }

    //递归操作，获取所有的子节点
    public static void getAllChildren(String path,ZooKeeper zk) throws Exception {
        List<String> children = zk.getChildren(path, null);
        for (String child : children) {
            if (path.equals("/")){
                System.out.println(path+child);//zookeeper   quota
                getAllChildren(path+child,zk);
            }else{
                System.out.println(path+"/"+child);//zookeeper   quota
                getAllChildren(path+"/"+child,zk);
            }
        }

    }
}
